import * as zrender from 'zrender'
// tick线、文本、分割线
class Tick extends zrender.Group {
    // 样式配置+位置
    constructor(config, tickData, index) {
        super();
        this.name = 'tick'
        this.tickConfig = {
            splitLine:{
                length: 400,
                style:{
                    stroke: 'rgba(0,0,0,0.2)',
                    lineWidth: 1,
                    lineDash: [5,5]
                }
            },
            tickLine:{
                length: 10,
                style:{
                    stroke: '#666'
                }
            },
            label:{
                offset: [0, 0],
                formatter: d=>d.toFixed(2),
                style:{
                    text: '',
                    fill: '#666'
                }
            },
        }
        this.index = index;
        this.config = config;
        this.tickData = tickData;
        zrender.util.merge(this.tickConfig, config.tick || {}, true)
        this.isX = this.config.XorY === 'x'
        let x = this.isX ? this.tickData[1] : this.config.start[0]
        let y = this.isX ? this.config.start[1] : this.tickData[1]
        this.position = [x,y]
        this.addTickLine();
        this.addTickLabel();
        this.addSplitLine();
    }

    addTickLine(){
        let tickLine = new zrender.Line({
            shape: {
                x1: 0,
                y1: 0,
                x2: (this.isX ? 0 : -this.tickConfig.tickLine.length),
                y2: (this.isX ? this.tickConfig.tickLine.length : 0),
            },
            style: this.tickConfig.tickLine.style
        })
        tickLine.name = 'tickLine'
        this.add(tickLine);
    }

    addTickLabel(){
        let label = new zrender.Text({
            x: (this.isX ? 0 : -this.tickConfig.tickLine.length) + this.tickConfig.label.offset[0],
            y: (this.isX ? this.tickConfig.tickLine.length : 0) + this.tickConfig.label.offset[1],
            style:{
                ...this.tickConfig.label.style,
                align: this.isX ? 'center' : 'right',
                verticalAlign: this.isX ? 'top' : 'center',
                text: this.tickConfig.label.formatter(this.tickData[0], this.index),
            }
        });
        label.name = 'label'
        this.add(label);
    }

    addSplitLine(){
        let splitLine = new zrender.Line({
            shape:{
                x1: 0,
                y1: 0,
                x2: (this.isX ? 0 : this.tickConfig.splitLine.length),
                y2: (this.isX ? -this.tickConfig.splitLine.length : 0),
            },
            style: this.tickConfig.splitLine.style,
            z: -1
        })
        splitLine.name = 'splitLine'
        this.add(splitLine)
    }
}

export default Tick